package cn.itcast.domain;
import cn.itcast.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class CakeDB {
    private static Map<Integer,Cake> cake =new LinkedHashMap<Integer, Cake>();
    static {
        try {
            //获取连接
            Connection conn = JDBCUtils.getConnection();
            //获取stmt对象
            Statement stmt = conn.createStatement();
            //定义sql语句，查询所有蛋糕
            String sql="select * from cake";
            //返回查询到的蛋糕结果集
            ResultSet rs = stmt.executeQuery(sql);
            //遍历结果集封装到Cake对象并添加到cake集合中
            while (rs.next()){
                int id=rs.getInt("id");
                String name=rs.getString("name");
                double price=rs.getDouble("price");
                Cake cake1=new Cake(id,name,price);
                cake.put(cake1.getId(),cake1);
            }
            //释放资源
            JDBCUtils.close(conn,stmt,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }
    // 获得所有的蛋糕
    public static Collection<Cake> getAll() {
        return cake.values();
    }
    // 根据指定的id获蛋糕
    public static Cake getCake(int id) {
        return cake.get(id);
    }
}
